package cn.edu.ldu.protocol;

import cn.edu.ldu.util.Consts;
import cn.edu.ldu.util.L;
import com.alibaba.fastjson.JSON;
import cn.edu.ldu.modules.controller.ChatHistoryController;
import cn.edu.ldu.views.modules.controller.UserController;
import cn.edu.ldu.modules.entity.ChatHistoryEntity;
import cn.edu.ldu.util.Translate;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

public class ChatWithFriend {

    public ChatWithFriend(Protocol pro) throws IOException {

        ChatHistoryEntity chatHistoryEntity = JSON.parseObject(pro.getData(), ChatHistoryEntity.class);
        chatHistoryEntity.setSendTime(Calendar.getInstance().getTime());
        Protocol protocol = new Protocol();
        protocol.setKey(Consts.P_CHAT_WITH_FRIEND);
        protocol.setData(JSONObject.toJSONString(chatHistoryEntity));

        if(!UserController.sendDataToUser(chatHistoryEntity.getTalkerId(), protocol)){
            chatHistoryEntity.setStatus(0);  //用户不在线
        }else {  //用户在线
            chatHistoryEntity.setStatus(1);
        }
        chatHistoryEntity.setSendTime(new Date());
        L.OK(chatHistoryEntity, ChatWithFriend.class);
        L.OK(pro, ChatWithFriend.class);
        try {
            ChatHistoryController.addChatHistory(chatHistoryEntity, pro.getToken());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
